package cn.com.common.job.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;

import cn.com.gas.entity.GasStationinfoEntity;

import cn.com.gas.entity.GasStaytimeResultEntity;

import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.thirdparty.entity.ZnGasStation;
import cn.com.thirdparty.mapper.GasDetectionSqlMapper;
import cn.com.thirdparty.mapper.ZnGasStationMapper;
import cn.com.util.TsBqUtils;

@Component("gasZnSynchronizationHistoryDataProcessTask")
@DisallowConcurrentExecution
public class GasZnSynchronizationHistoryDataProcessTask {

	// 未使用
	@Value("${gasstation.timedTask.gasStationMonthForecastProcessTask}")
	private String gasStationMonthForecastProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GasStationinfoService stationinfoService;
	@Autowired
	private GasStaytimeResultService staytimeResultService;
	@Autowired
	private ZnGasStationMapper znGasStationMapper;
	@Autowired
	private GasDetectionSqlMapper gasDetectionSqlMapper;

	public void run(String params) throws Exception {
		logger.debug("gasStationMonthForecastProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasStationMonthForecastProcessTask：{}", gasStationMonthForecastProcessTask);

		if (gasStationMonthForecastProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasStationMonthForecastProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasStationMonthForecastProcessTask定时任务");
		}

		DateTimeFormatter _formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate yesterday = LocalDate.now().minusDays(1);
		LocalDateTime startOfYesterday = LocalDateTime.of(yesterday, LocalTime.MIN);
		LocalDateTime endOfYesterday = LocalDateTime.of(yesterday, LocalTime.MAX);

		String time = startOfYesterday.format(_formatter);

		if (TsBqUtils.isNotNull(params)) {

			String[] _paramsArr = params.split("_");

			for (String _params : _paramsArr) {

				DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
				LocalDate localDate = LocalDate.parse(_params, formatter1);
				startOfYesterday = LocalDateTime.of(localDate, LocalTime.MIN);
				endOfYesterday = LocalDateTime.of(localDate, LocalTime.MAX);
				time = localDate.format(_formatter);

				logger.debug("gasStationAndCamForecastProcessTask定时任务正在执行，加工日期：{}", _params);
				handleData(startOfYesterday, endOfYesterday, time, _formatter);
				logger.debug("gasStationAndCamForecastProcessTask定时任务正在执行，加工完成：{}", _params);

			}

		} else {

		}
	}

	private void handleData(LocalDateTime startOfYesterday, LocalDateTime endOfYesterday, String time,
			DateTimeFormatter _formatter) throws ParseException {
		try {
			
			LambdaQueryWrapper<GasStaytimeResultEntity> queryStaytimeResult = Wrappers.lambdaQuery();
			
	        Date startOfYesterdayDate = Date.from(startOfYesterday.atZone(ZoneId.systemDefault()).toInstant());
	        Date endOfYesterdayDate = Date.from(endOfYesterday.atZone(ZoneId.systemDefault()).toInstant());
			
			queryStaytimeResult.ge(GasStaytimeResultEntity::getMessageDisappear, startOfYesterdayDate);
			queryStaytimeResult.le(GasStaytimeResultEntity::getMessageDisappear, endOfYesterdayDate);
			List<GasStaytimeResultEntity> staytimeResultList = staytimeResultService.list(queryStaytimeResult);
			logger.debug("staytimeResultList获取数据" + staytimeResultList.size() + "条,时间：" + startOfYesterday + "--" + endOfYesterday);
			
			
			if (TsBqUtils.isNotNull(staytimeResultList)) {

				for (GasStaytimeResultEntity entity : staytimeResultList) {
					String stationId = entity.getStationId();
					
					GasStationinfoEntity gasStationinfoEntity = stationinfoService.getById(stationId);
					
					if(TsBqUtils.isNotNull(gasStationinfoEntity)){
						
						String thirdPartyId = gasStationinfoEntity.getThirdPartyId();
						
						if(TsBqUtils.isNotNull(thirdPartyId)){
							ZnGasStation znGasStation = znGasStationMapper.selectById(thirdPartyId);
							
							if(TsBqUtils.isNotNull(znGasStation)){

								String vehicleType = "";
								if ("汽油".equals(entity.getOils())) {
									vehicleType = "1";
								} else {
									vehicleType = "8";
								}

								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
								sdf.setLenient(false); // 设置严格模式，不允许解析不严格对应格式的日期
								String image1 = "";
								if(TsBqUtils.isNotNull(entity.getImage1())){
									image1 = entity.getImage1();
								}else{
									image1 = entity.getImage();
								}
								
								long costTime = (sdf.parse(entity.getMessageDisappear()).getTime()
										- sdf.parse(entity.getMessageAppear()).getTime()) / 1000l;

								if (znGasStation.getIsNormal() == 1 && znGasStation.getIsValid() == 1) {
									
									String sql = "INSERT INTO gas_detection_out_1_" + time.substring(0, 4) + "_" + time.substring(5, 7)
											+ " "
											+ "(id, annotationId, stationId, indexCode, startImg, endImg, startTime, endTime, createTime, costTime, vehicleType)"
											+ " VALUES ('" + TsBqUtils.getUUID() + "', '" + TsBqUtils.getUUID() + "', "
											+ gasStationinfoEntity.getThirdPartyId() + ", 'indexCode', '" + entity.getImage() + "', '"
											+ image1 + "', '" + entity.getMessageAppear() + "', '"
											+ entity.getMessageDisappear() + "', SYSDATE(), " + costTime + ", " + vehicleType + ")";

									logger.debug("执行sql:" + sql);

									gasDetectionSqlMapper.gasDetectionInsertInto(sql);

								} else {
									logger.debug("加油站数据不传IsNormalIsValid:" + znGasStation.getIsNormal() + znGasStation.getIsValid());

								}
								
							}else{
								logger.debug("通过thirdPartyId未获取到znGasStation:" + thirdPartyId);

							}
							
						}else{
							logger.debug("通过gasStationinfoEntity未获取到thirdPartyId:" + stationId);

						}
						
					}else{
						logger.debug("通过stationId未获取到gasStationinfoEntity:" + stationId);

					}
					
				}
			}
			
			
		} catch (Exception e) {
			logger.debug("gasStationMonthForecastProcessTask定时任务该条数据为写入成功，原因：" + e.getMessage());
		}
		
	}

}
